<?php
/**
 * 图片上传类，也可上传其它类型的文件
 *
 * @author
 */

class XUpload
{
    /**
     * 上传单张图片
     * @param $upload //文件名
     * @param $type //用户指定目录
     * @param $act //动作：create或update
     * @param string $imgUrl //图片地址
     * @return bool|string
     */
    public static function createFile($upload, $imgUrl, $type = '', $act = 'update')
    {
        //更新图片
        if (!empty($imgUrl) && $act === 'update') {
            $deleteFile = Yii::app()->basePath . '/../' . $imgUrl;
            if (file_exists($deleteFile))
                unlink($deleteFile);
        }

        //上传图片
        //根据时间戳和随机数重命名文件名，extensionName是获取文件的扩展名
        $imgName = date('Ymd') . '-' . uniqid() . '.' . $upload->extensionName;
        if(!empty($type)){
            $uploadDir = Yii::app()->basePath . '/../uploads/' . $type . '/' . date('Ym', time());
            $imageUrl = '/uploads/' . $type . '/' . date('Ym', time()) . '/' . $imgName;
        }else{
            $uploadDir = Yii::app()->basePath . '/../uploads/' . date('Ym', time());
            $imageUrl = '/uploads/' . date('Ym', time()) . '/' . $imgName;
        }
        self::recursionMkDir($uploadDir);

        //存储绝对路径
        $uploadPath = $uploadDir . '/' . $imgName;
        if ($upload->saveAs($uploadPath)) {
            return $imageUrl;
        } else {
            return false;
        }
    }

    //创建目录
    private static function recursionMkDir($dir)
    {
        if (!is_dir($dir)) {
            if (!is_dir(dirname($dir))) {
                self::recursionMkDir(dirname($dir));
                mkdir($dir, '0777');
            } else {
                mkdir($dir, '0777');
            }
        }
    }

    /**
     * 多文件上传
     * @param $model
     * @param $attr
     * @param $path
     * @return mixed
     */
    public static function uploadMultiFile($model, $attr, $path='/uploads/')
    {
        /*
         * path when uploads folder is on site root.
         * $path='/uploads/'
         */
        if($imageFile = CUploadedFile::getInstances($model, $attr)){

            foreach ($imageFile as $i=>$file){

                $imgName = date('Ymd') . '-' . uniqid() . '.' . $file->getExtensionName();
                $uploadDir = Yii::app()->basePath . '/../uploads/' . date('Ym', time());
                $imageUrl = '/uploads/' . date('Ym', time()) . '/' . $imgName;
                //创建目录
                self::recursionMkDir($uploadDir);
                $uploadPath = $uploadDir . '/' . $imgName;

                // $formatName=time().$i.'.'.$file->getExtensionName();
                //$fileName = "{$imageFile[$i]}";
                //$formatName = time().$i.'_'.$fileName;
                $file->saveAs($uploadPath);
                $fFile[$i] = $imageUrl;
            }
            return ($fFile);
        }
    }

}